<template>
  <div class="scroll-view" ref="scrollView" @scroll="handleScroll">
    <div v-for="(item, index) in list" :key="index" class="list-item">
      列表项{{ item }}
    </div>
  </div>
  <br />

  <div class="scroll-view2">
    <el-scrollbar ref="scrollbarView">
      <div v-for="(item, index) in list" :key="index" class="list-item">
        列表项{{ item }}
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';

// 列表数据
const list = ref([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
// 滚动容器引用
const scrollView = ref(null);
const scrollbarView = ref(null);

// 滚动事件处理函数
const handleScroll = (e) => {
  // 解构获取滚动相关属性
  const { scrollTop, clientHeight, scrollHeight } = e.target;
  console.log('原生滚动 - scrollTop', scrollTop, 'clientHeight', clientHeight, 'scrollHeight', scrollHeight);
  // 检测是否滚动到底部（考虑浏览器计算精度问题，使用>=）
  if (scrollTop + clientHeight >= scrollHeight - 0.5) {
    ElMessage('原生滚动到底部啦');
  }
};

// Element Plus滚动条滚动处理函数
const handlescrollbar = (e) => {
  // 正确获取Element Plus滚动条的滚动容器
  // 从事件对象中获取滚动目标
  const scrollContainer = e.target;
  if (scrollContainer) {
    const { scrollTop, clientHeight, scrollHeight } = scrollContainer;
    console.log(scrollTop, clientHeight, scrollHeight);
    // 检测是否滚动到底部
    if (scrollTop + clientHeight >= scrollHeight) {
      list.value.push(...[11, 12, 13, 14, 15]);
      ElMessage('Element Plus滚动到底部啦');
    }
  }
};

// 在组件挂载后绑定Element Plus滚动条的事件
onMounted(() => {
  if (scrollbarView.value) {
    // 获取内部滚动容器元素
    const wrapElement = scrollbarView.value.$el.querySelector('.el-scrollbar__wrap');
    if (wrapElement) {
      wrapElement.addEventListener('scroll', handlescrollbar);
    }
  }
});

// 组件卸载前移除事件监听
onBeforeUnmount(() => {
  if (scrollbarView.value) {
    const wrapElement = scrollbarView.value.$el.querySelector('.el-scrollbar__wrap');
    if (wrapElement) {
      wrapElement.removeEventListener('scroll', handlescrollbar);
    }
  }
});
</script>

<style scoped>
.scroll-view {
  width: 400px;
  height: 300px;
  overflow-y: scroll;
  background-color: #68b687;
}

.scroll-view2 {
  width: 400px;
  height: 200px;
  background-color: #68b687;
  border: 1px solid #68b687;
  border-radius: 8px;
  padding: 0;
  /* 确保内部元素不会超出圆角 */
  overflow: hidden;
}

.el-scrollbar {
  height: 100%;
}

.list-item {
  height: 50px;
  padding: 0;
  background-color: rgba(0, 0, 0, .2);
  /* 字体居中 */
  text-align: center;
  /* 行高与元素高度一致，实现上下居中 */
  line-height: 50px;
}

.list-item:nth-child(2n) {
  background-color: rgba(222, 221, 221, 0.2);
}
</style>